<template>
  <div id="login">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item id="lo">用户登录</el-form-item>
      <el-form-item label="" prop="username">
        <el-input v-model="form.username" placeholder="请输入账号" prefix-icon="el-icon-user"></el-input>
      </el-form-item>
      <el-form-item label="" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入密码" prefix-icon="el-icon-lock" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="checked">七天自动登录</el-checkbox>
      </el-form-item>
      <el-form-item id="btn">
        <el-button type="primary" class="btn" @click="onSubmit('form')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data: function () {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        password: [
          { required: true, message: '密码不可为空', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '账号不可为空', trigger: 'blur' }
        ]
      },

      checked: true
    }
  },
  methods: {

    onSubmit: function (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //向后台发送ajax请求
          this.$axios({
            url: '/user/login',
            params: this.form,
          }).then((res) => {
            if (res.data.msg == '登录成功') {
              this.$message({
                message: '登录成功',
                type: 'success',
              });
              this.$router.push({ name: 'home/homepage' })
              sessionStorage.setItem('user', JSON.stringify(res.data.data[0]));
              sessionStorage.setItem('token', res.data.token)
            } else if (res.data.msg == '无数据') {
              this.$message({
                message: '账号或密码错误',
                type: 'info',
              });
            }
          })
        } else {
          return false;
        }
      });

    }

  }
}
</script>
<style scoped>
#login {
  height: 100%;
  background: url(../assets/images/login-bg.jpg);
  background-size: cover;
}
#lo {
  text-align: center;
}
.el-form {
  width: 500px;
  height: 400px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -210px;
  margin-top: -160px;
  background: rgba(255, 255, 255, 0.3);
  padding-top: 50px;
  padding-right: 80px;
}
#btn {
  text-align: center;
}
.btn {
  width: 340px;
}
</style>
